import json
from django.http import HttpResponse
from . import query

def hello(request):
    return HttpResponse('This is home page.')


def get_info(request):
    err = 0
    if not request.POST:
        testmsg = {'responseCode':0}
        return HttpResponse(json.dumps(testmsg, ensure_ascii=False))
    errmsg = {'responseCode':900000}
    if 'serialNo' not in request.POST or request.POST['serialNo'] == '':
        errmsg['responseMsg'] = 'lose series'
        err = 1    
    elif 'mode' not in request.POST or request.POST['mode'] == '':
        errmsg['responseMsg'] = 'lose mode'
        err = 1
    elif 'bankId' not in request.POST or request.POST['bankId'] == '':
        errmsg['responseMsg'] = 'lose bank'
        err = 1
    if err == 1:
        errjson = json.dumps(errmsg, ensure_ascii=False)
        return HttpResponse(errjson)
    mode = int(request.POST['mode'])
    bank = int(request.POST['bankId'])
    series = request.POST['serialNo']
    name = 'ABC'
    idNo = '123456789012345678'
    phoneNo = '12345678901'
    if 'name' in request.POST and request.POST['name'] != '':
        name = request.POST['name']
    if 'idCardNo' in request.POST and request.POST['idCardNo'] != '':
        idNo = request.POST['idCardNo']
    if 'phoneNo' in request.POST and request.POST['phoneNo'] != '':
        phoneNo = request.POST['phoneNo']
    optNo = ''
    verifyNo = ''
    if 'verifyImage' in request.POST:
        optNo = request.POST['verifyImage']
        if optNo == '':
            optNo = 'ABCD'
    if 'smsCode' in request.POST:
        verifyNo = request.POST['smsCode']
        if verifyNo == '':
            verifyNo = '123456'

    msg = query.parse(series, mode, bank, idNo, phoneNo, optNo, verifyNo)
    if mode == 1:
        information = {}
        information['name'] = name
        information['idNo'] = idNo
        information['phoneNo'] = phoneNo
        information['detail'] = msg['textAll']

        with open('./data/info.txt', 'a', encoding='utf-8') as f:
            f.write(json.dumps(information, ensure_ascii=False))
            f.write('\n')
    return HttpResponse(json.dumps(msg, ensure_ascii=False))
